const router = require('koa-router')()
const {
    getAllBlog,
    getDetail,
    updateBlog,
    delBlog,
    sendNewBlog,
    replyBlog,
    getReply
} = require('../controller/blog')
const { SuccessModel, ErrorModel } = require('../model/resModel')
const loginCheck = require('../middleware/loginCheck')

router.prefix('/api/blog')

// 回帖 
router.post('/reply',loginCheck, async function (ctx, next) {

    const body = ctx.request.body
    let rtid = body.rtid || ''
    let rsid = body.rsid || ''
    let ruid = body.ruid || ''
    let rcontent = body.rcontent || ''
    let rCount = body.rCount || 0
    rCount = rCount + 1
    let rtime = Date.now()

    
    
    const listData = await replyBlog(rtid, rsid, ruid, rcontent, rtime, rCount)
    ctx.body = new SuccessModel(listData)
})

// 获取 帖子回复
router.get('/getreply', async function (ctx, next) {
    let tid = ctx.query.tid || ''

    console.log(tid);

    const listData = await getReply(tid)

    ctx.body = new SuccessModel(listData)
})

// 发帖 
router.post('/new',loginCheck, async function (ctx, next) {

    let request = ctx.request.body
    let tsid = request.tsid || ''
    let tuid = request.tuid || ''
    let ttopic = request.ttopic || ''
    let tcontent = request.tcontent || ''
    let ttime = Date.now()

    const listData = await sendNewBlog(tsid, tuid, ttopic, tcontent, ttime)
    ctx.body = new SuccessModel(listData)
})

// 拿 所有帖子 可选参数 > 指定用户，关键字
router.get('/all', async function (ctx, next) {
    let tuid = ctx.query.tuid || ''
    let keyword = ctx.query.keyword || ''
    let tsid = ctx.query.tsid || ''

    if (ctx.query.isadmin) {
        console.log('is admin')
        // 管理员界面
        if (ctx.session.username == null) {
            console.error('is admin, but no login')
            // 未登录
            ctx.body = new ErrorModel('未登录')
            return
        }
        // 强制查询自己的博客
        author = ctx.session.username
    }
    const listData = await getAllBlog(tuid, keyword, tsid)

    ctx.body = new SuccessModel(listData)
})

//点击帖子标题 查看帖子
router.get('/detail', async function (ctx, next) {
    const data = await getDetail(ctx.query.tid, ctx.query.clickcount)
    ctx.body = new SuccessModel(data)
})

router.post('/update', loginCheck,async function (ctx, next) {

    const val = await updateBlog(ctx.request.body)
    if (val) {
        ctx.body = new SuccessModel()
    } else {
        ctx.body = new ErrorModel('更新博客失败')
    }
})

// 删帖  未完成
router.post('/del',loginCheck, async function (ctx, next) {
    const author = ctx.session.username
    const val = await delBlog(ctx.query.id, author)
    if (val) {
        ctx.body = new SuccessModel()
    } else {
        ctx.body = new ErrorModel('删除博客失败')
    }
})

module.exports = router
